package com.liannong.controller;

import com.liannong.common.Result;
import com.liannong.entity.Product;
import com.liannong.service.ProductService;
import com.liannong.service.BlockchainService;
import com.liannong.vo.ProductVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/product")
public class ProductController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductService productService;

    @Autowired
    private BlockchainService blockchainService;

    /**
     * 添加商品
     * @param product 商品信息
     * @return 添加结果
     */
    @PostMapping("/save")
    public Result save(@RequestBody Product product) {
        boolean success = productService.save(product);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }
    
    /**
     * 删除商品
     * @param productId 商品ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{productId}")
    public Result delete(@PathVariable Long productId) {
        boolean success = productService.removeById(productId);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }
    
    /**
     * 批量删除商品
     * @param ids 商品ID集合
     * @return 删除结果
     */
    @PostMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Long> ids) {
        boolean success = productService.removeByIds(ids);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 获取商品列表
     * @return 商品列表
     */
    @GetMapping("/list")
    public Result getProductList() {
        try {
            List<ProductVO> products = productService.getProductList();
            return Result.success(products);
        } catch (Exception e) {
            logger.error("获取商品列表失败", e);
            return Result.error("500", "获取商品列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取商品详情
     * @param productId 商品ID
     * @return 商品详情
     */
    @GetMapping("/detail/{productId}")
    public Result getProductDetail(@PathVariable Long productId) {
        try {
            ProductVO product = productService.getProductDetail(productId);
            if (product == null) {
                return Result.error("404", "商品不存在");
            }
            return Result.success(product);
        } catch (Exception e) {
            logger.error("获取商品详情失败", e);
            return Result.error("500", "获取商品详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新商品信息
     * @param product 商品信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public Result update(@RequestBody Product product) {
        boolean success = productService.updateById(product);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 根据温度区间查询商品
     * @param minTemp 最低温度
     * @param maxTemp 最高温度
     * @return 商品列表
     */
    @GetMapping("/temperature")
    public Result findByTemperature(
            @RequestParam Integer minTemp,
            @RequestParam Integer maxTemp) {
        List<ProductVO> productList = productService.getProductsByTemperature(minTemp, maxTemp);
        return Result.success(productList);
    }

    /**
     * 根据溯源码获取商品ID
     * @param traceCode 溯源码
     * @return 商品ID
     */
    @GetMapping("/getIdByTraceCode/{traceCode}")
    public Result getIdByTraceCode(@PathVariable String traceCode) {
        try {
            Long productId = productService.getProductIdByTraceCode(traceCode);
            if (productId != null) {
                return Result.success(productId);
            } else {
                return Result.error("400", "未找到该溯源码对应的商品");
            }
        } catch (Exception e) {
            logger.error("根据溯源码获取商品ID失败", e);
            return Result.error("500", "服务器错误");
        }
    }

    /**
     * 果农添加商品
     * @param product 商品信息
     * @param userId 果农用户ID
     * @return 添加结果
     */
    @PostMapping("/farmer/add")
    public Result addProductByFarmer(@RequestBody Product product, @RequestParam Integer userId) {
        logger.info("果农添加商品请求 - userId: {}, productName: {}", userId, product.getName());
        
        try {
            boolean success = productService.addProductByFarmer(product, userId);
            if (success) {
                return Result.success(product.getProductId());
            } else {
                return Result.error("400", "添加商品失败");
            }
        } catch (Exception e) {
            logger.error("果农添加商品失败", e);
            return Result.error("500", "添加商品失败: " + e.getMessage());
        }
    }

    /**
     * 审核产品
     * @param productId 产品ID
     * @param auditData 审核数据
     * @return 审核结果
     */
    @PostMapping("/admin/audit/{productId}")
    public Result auditProduct(
            @PathVariable("productId") Integer productId,
            @RequestBody Map<String, Object> auditData) {
        try {
            boolean approved = (boolean) auditData.get("approved");
            String comment = (String) auditData.get("comment");
            Integer auditUserId = (Integer) auditData.get("auditUserId");
            
            // 调用审核方法
            boolean success = productService.auditProduct(
                productId,
                auditUserId,
                approved ? 1 : 2, // 1-通过，2-拒绝
                comment
            );
            
            if (success && approved) {
                // 获取产品信息
                ProductVO productVO = productService.getProductDetail(productId.longValue());
                if (productVO != null) {
                    // 将产品信息提交到区块链
                    Product product = new Product();
                    product.setProductId(productId);
                    product.setTraceCode(productVO.getTraceCode());
                    product.setMinTemp(productVO.getMinTemp());
                    product.setMaxTemp(productVO.getMaxTemp());
                    
                    boolean blockchainSuccess = blockchainService.createQualityRecord(product);
                    if (blockchainSuccess) {
                        return Result.success("审核通过，数据已提交到区块链");
                    } else {
                        return Result.error("500", "审核通过，但区块链提交失败");
                    }
                }
            }
            
            return success ? 
                Result.success("审核完成") : 
                Result.error("500", "审核失败");
        } catch (Exception e) {
            logger.error("审核失败", e);
            return Result.error("500", "审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取待审核的产品列表
     * @return 待审核产品列表
     */
    @GetMapping("/admin/pending")
    public Result getPendingAuditProducts() {
        logger.info("获取待审核商品列表请求");
        
        try {
            List<ProductVO> products = productService.getPendingAuditProducts();
            return Result.success(products);
        } catch (Exception e) {
            logger.error("获取待审核商品列表失败", e);
            return Result.error("500", "获取待审核商品列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取果农创建的产品列表
     * @param farmerId 果农ID
     * @return 产品列表
     */
    @GetMapping("/farmer/list")
    public Result getProductsByFarmer(@RequestParam Integer farmerId) {
        logger.info("获取果农创建的商品列表请求 - farmerId: {}", farmerId);
        
        try {
            List<ProductVO> products = productService.getProductsByFarmer(farmerId);
            return Result.success(products);
        } catch (Exception e) {
            logger.error("获取果农创建的商品列表失败", e);
            return Result.error("500", "获取果农创建的商品列表失败: " + e.getMessage());
        }
    }

    /**
     * 提交温度记录
     * @param traceCode 溯源码
     * @param temperature 温度
     * @return 提交结果
     */
    @PostMapping("/temperature/{traceCode}")
    public Result submitTemperature(
            @PathVariable("traceCode") String traceCode,
            @RequestParam("temperature") Integer temperature) {
        try {
            boolean success = blockchainService.submitTemperatureRecord(traceCode, temperature);
            if (success) {
                return Result.success("温度记录提交成功");
            } else {
                return Result.error("500", "温度记录提交失败");
            }
        } catch (Exception e) {
            logger.error("温度记录提交失败", e);
            return Result.error("500", "温度记录提交失败：" + e.getMessage());
        }
    }

    /**
     * 查询质量状态
     * @param traceCode 溯源码
     * @return 质量状态信息
     */
    @GetMapping("/quality/{traceCode}")
    public Result checkQualityStatus(@PathVariable("traceCode") String traceCode) {
        try {
            Map<String, Object> status = blockchainService.checkQualityStatus(traceCode);
            if (status != null) {
                return Result.success(status);
            } else {
                return Result.error("500", "质量状态查询失败");
            }
        } catch (Exception e) {
            logger.error("质量状态查询失败", e);
            return Result.error("500", "质量状态查询失败：" + e.getMessage());
        }
    }
} 